#include "udpserverthread.h"
#include <QDebug>

UDPServerThread::UDPServerThread(QString ip, int port)
{
    this->ip = ip;
    this->port = port;
}

int UDPServerThread::initServer()
{
    try{
        udpSocket = new QUdpSocket(this);
        udpSocket->bind(QHostAddress(ip), port);
        isReady = true;
        isConnected = true;
        return 0;
    }catch(const std::exception& ex){
        qDebug() << "Error";
        isReady = false;
        return -1;
    }
}

void UDPServerThread::run()
{
    qDebug()<<"UDP thread collector " << QThread::currentThreadId()<<"receive";
    parser = new UDPParser;
    while(isReady) {

        QByteArray ba;
            if(udpSocket->hasPendingDatagrams())
            {
                ba.resize(udpSocket->pendingDatagramSize());
                udpSocket->readDatagram(ba.data(), ba.size());
                udpInfo *currUdpData = (udpInfo*) ba.data();
//                parser->parseSinglePackage(ba);
                qDebug() << "Thread: " << *currUdpData;
                emit parsedData(currUdpData);
            }

    }
    qDebug() << "HERE end";
}
void UDPServerThread::stopCollector()
{
    isReady = false;
//    lock.unlock();
}

void UDPServerThread::closeServer(){
    if(isConnected)
        udpSocket->close();
    isReady = false;
    isConnected = false;
}

UDPServerThread::~UDPServerThread()
{
    delete udpSocket;
}
